12. Prevent Crash with Blank Editor

Prevent Crash with Blank Editor

Question:

Awesome Work!

The major functionality of the EditorActivity in edit mode has been completed.

Next Steps

We still need to implement deleting and fix up a few bugs. For example, if you open up the EditorActivity when inserting a new pet, and then accidentally hit the save button without typing anything…we get a crash.

If we look at the error, we can see that it’s upset that we didn’t enter a number for weight; basically it can’t convert a blank space into a number.

Also, if we take a look at the contacts app, you’ll notice that it doesn’t enter a blank contact when you save one.
In general, we should require, from the UI, that the user enters something about the pet before even trying to put it into a database. All blank values should be considered the user just pressing the save button accidentally and not a new pet.

Your Task

Your task is to solve this bug. To do this, you should check whether the inputs are empty. You can use the method TextUtils.isEmpty() to check whether a string is made up of all whitespace or nothing at all. If all of the inputs are empty, and the gender isn’t updated from GENDER UNKNOWN then the save pet method should simply return without saving anything.

In addition, when you save a new pet without a weight, the weight given to the pet should be zero and it should not crash.

Start Quiz:

Solution:

Solution code

All the changes we need to make are in the EditorActivity.java file, specifically within the savePet() method.

To solve the first issue, right after we get all the values but before we make the ContentValues object, I’ll add an if statement to check if they are all empty and if the gender is unknown. If so, I won’t even bother with the rest of the method or inserting the pet and instead will just return.

 if (mCurrentPetUri == null &&
         TextUtils.isEmpty(nameString) && TextUtils.isEmpty(breedString) &&
         TextUtils.isEmpty(weightString) && mGender == PetEntry.GENDER_UNKNOWN) {return;}

The next issue I’ll solve right before placing the weight into the content value object. If the weight is not specified, it should be set to zero and should not cause a crash. So in the code, I’ll set the weight to 0 by default, and then, if the weight has been entered, I’ll change it to that integer value.

   // If the weight is not provided by the user, don't try to parse the string into an
    // integer value. Use 0 by default.
    int weight = 0;
    if (!TextUtils.isEmpty(weightString)) {
        weight = Integer.parseInt(weightString);
    }
    values.put(PetEntry.COLUMN_PET_WEIGHT, weight);

And with those changes, the app doesn’t crash, nor does it store completely empty pets. Well done!

INSTRUCTOR NOTE:

Hint: TextUtils.isEmpty(String s) returns true if the input String is null or empty.